<template>
  <div class="common-layout" style="height: auto">
    <el-container>
      <el-header style="padding: 0;margin: 0">
        <el-affix :offset="0">
          <div id="headDiv">
            <div>
              <el-button type="warning" size="large" style="margin-left: 40px" @click="$router.push('app')" round>
                <el-icon>
                  <House/>
                </el-icon>
                首页
              </el-button>
            </div>
            <div :hidden="userLogin">
              <span style="color: #626262;margin-right: 20px">您好!</span>
              <el-button type="primary" size="large" @click="$router.push('goods')" round>全部商品</el-button>
              <el-button type="primary" size="large" @click="toShoppingCar()" round>购物车</el-button>
              <el-button size="large" type="primary" @click="toOrder()" round>个人订单</el-button>
              <el-button size="large" type="primary" @click="$router.push('user')" round>个人信息</el-button>
              <el-button size="large" type="primary" @click="$router.push('returnOrder')" round>
                退款订单管理
              </el-button>
              <el-button size="large" type="primary" @click="$router.push('userMoney')" round>预存款管理</el-button>
              <el-button size="large" type="danger" style="margin-right: 20px" @click="exitUser()" round>退出登录
              </el-button>
            </div>
          </div>
        </el-affix>
      </el-header>
    </el-container>
  </div>
  <div style="width: auto;margin: 0 auto;height: auto">
    <div style="font-size: 30px;margin: 20px 0">
      <a href="#" style="color:#545454;text-decoration: none;">LO<span style="color: #c4c4c4">V</span><span>O</span> | 朗沃商城</a>
    </div>
  </div>
  <div style="width: auto;margin: 0 auto;height: 200px;">
    <div style="display:flex;justify-content: space-between;margin-top: 20px">
      <el-select v-model="selectAddress" placeholder="请选择收货地址" @change="changeAddress" style="width: 300px">
        <el-option
            v-for="item in addressOptions"
            :key="item.addressId"
            :label="item.receiverRegion+' '+item.receiverAddress"
            :value="item.addressId"
        >
        </el-option>
      </el-select>
      <el-button size="large" type="primary" style="margin-right: 80px;margin-bottom: 20px" @click="checkout()">结算</el-button>
    </div>
    <el-table :data="productList"  @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="40" />-->
      <el-table-column label="商品信息" align="center">
        <template #default="product">
          <div style="width: 240px;display: flex;">
            <div>
              <el-image :src="actionUrl+product.row.goodsPic" style="width:100px;height: 100px;"></el-image>
            </div>
            <div>
              <span style="margin-left: 10px">{{product.row.goodsName}}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center">
        <template #default="product">
          <span style="font-size: 20px;"><span>{{product.row.goodsType}}</span></span>
        </template>
      </el-table-column>
      <el-table-column label="商品规格" align="center">
        <template #default="product">
          <span style="font-size: 20px;"><span>{{product.row.goodsSize}}</span></span>
        </template>
      </el-table-column>
      <el-table-column label="商品单价" align="center">
        <template #default="product">
          <span style="font-size: 20px;"><strong>{{product.row.sellPrice}}</strong></span>
        </template>
      </el-table-column>
      <el-table-column label="商品数量" align="center">
        <template #default="product">
          <el-input-number v-model="product.row.buyNum" :min="1" :max="99" @change="handleChange(product.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center">
        <template #default="product">
          <span style="font-size: 20px;color: red"><strong>{{product.row.buyNum*product.row.sellPrice}}</strong></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="product">
        <el-button type="primary" size="large" @click="removeCar(product.row.goodsNo)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-dialog v-model="showCheckout">
    <div style="display: flex;justify-content: space-around;margin-top: 20px">
      <span style="color: black;font-size: 20px">商品总价：{{moneyVo.totalMoney}}</span>
      <span style="color: green;font-size: 20px">折后价：{{moneyVo.totalPrice}}</span>
      <span style="color: orange;font-size: 20px">预存款支付折后价：{{moneyVo.preTotalPrice}}</span>
    </div>
    <template #footer>
      <el-button type="primary" @click="pay(1)">预存款支付</el-button>
      <el-button type="primary" @click="pay(0)">支付宝支付</el-button>
      <el-button @click="closeDiv">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {ElMessage} from "element-plus";
import axios from "axios";

export default {
  name: "ShoppingCar",
  data(){
    return{
      userToken:"",
      actionUrl: "/picture/face/",
      productList:[],
      selectProducts:[],
      total:0,
      showCheckout:false,
      selectAddress:'',
      ackAddress:{},
      addressOptions:[],
      moneyVo:{}
    }
  },
  created() {
    // let userToken = sessionStorage.getItem("userToken")
    // if (userToken==null){
    //   this.$router.push("login")
    // }else {
    //   this.userToken=userToken
    // }
    this.readCar();
    this.queryAddress();//查询用户地址
  },
  methods:{
    readCar(){
      axios.get("/api/shoppingCar/readCar/"+sessionStorage.getItem("userId")+"").then(res=>{
        console.log(res.data)
        this.productList=res.data;
      })
    },
    //退出登录
    exitUser(){
      sessionStorage.clear();
      this.$router.push("newLogin")
    },
    //修改购买数量
    handleChange(row){
      console.log(row)
      row.userId = sessionStorage.getItem("userId")
      axios.post("/api/shoppingCar/updateCar",row).then(res=>{
        console.log(res.data.msg)
      })
    },
    //删除购物车商品
    removeCar(goodsNo){
      let param = new URLSearchParams();
      param.append("userId",sessionStorage.getItem("userId"));
      param.append("goodsNo",goodsNo);
      axios.post("/api/shoppingCar/removeCar",param).then(res=>{
        if (res.data.code == 200) {
          this.showShoppingCar = false
          ElMessage.success(res.data.msg);
          this.readCar()
        } else {
          this.showShoppingCar = false
          ElMessage.error(res.data.msg);
          this.readCar()
        }
      })
    },
    //结算dialog
    checkout(){
        this.showCheckout=true;
        let param = new URLSearchParams();
        param.append("userId",sessionStorage.getItem("userId"))
        param.append("userDiscount",sessionStorage.getItem("userDiscount"))
        axios.post("/api/shoppingCar/getMoney",param).then(res=>{
          console.log(res.data)
          this.moneyVo = res.data
        })
    },
    pay(payMethod){
      console.log(JSON.stringify(this.ackAddress))
      let param = new URLSearchParams();
      param.append("userId",sessionStorage.getItem("userId"))
      param.append("userNo",sessionStorage.getItem("userNo"))
      param.append("payMethod",payMethod)
      param.append("address",JSON.stringify(this.ackAddress))
      param.append("userDiscount",sessionStorage.getItem("userDiscount"))
      param.append("totalPrice",this.moneyVo.totalPrice)
      param.append("totalMoney",this.moneyVo.totalMoney)
      param.append("preTotalPrice",this.moneyVo.preTotalPrice)
      console.log(param)
      axios.post("/api/shoppingCar/buy",param).then(res=>{
        if(res.data.code===200){
          if(payMethod===0){
            console.log(res.data)
            window.open("/api/pay/alipay/"+res.data.data.orderNo+"/"+res.data.data.totalPrice+"/"+sessionStorage.getItem("userId")+"")
            this.renovate(true)
          }
          ElMessage.success(res.data.msg)
          this.readCar()
        }else {
          ElMessage.error(res.data.msg)
        }
      })
      this.closeDiv();
    },
    //关闭dialog
    closeDiv(){
      this.showCheckout=false
    },
    //查询收货地址
    queryAddress(){
      axios.get('api/address/queryAddress?userNo='+sessionStorage.getItem('userNo')).then(p=>{
        if (p.data.code===200){
          this.addressOptions=p.data.data;
          for (let i = 0; i < this.addressOptions.length; i++) {
            if (this.addressOptions[i].defaultAddress===1){
              this.selectAddress=this.addressOptions[i].addressId;
              this.ackAddress=this.addressOptions[i];
              break;
            }
          }
        }else{
          ElMessage.error(p.data.msg);
        }

      })
    },
    changeAddress(){
      for (let i = 0; i < this.addressOptions.length; i++) {
        if (this.addressOptions[i].addressId===this.selectAddress){
          this.ackAddress=this.addressOptions[i];
          break;
        }
      }
      console.log(this.ackAddress)
    },
    toShoppingCar(){
      let str = sessionStorage.getItem("user")
      let user = JSON.parse(str)
      console.log(user)
      if(user.auditStatus===1){
        this.$router.push('shoppingCar')
      }else{
        ElMessage.error("用户资质还未通过")
      }
    },
    toOrder(){
      let str = sessionStorage.getItem("user")
      let user = JSON.parse(str)
      console.log(user)
      if(user.auditStatus===1){
        this.$router.push('order')
      }else{
        ElMessage.error("用户资质还未通过")
      }
    },
    renovate(status){
      while (status){
        if(sessionStorage.getItem("renovate")==='1'){
          this.readCar();
          sessionStorage.setItem("renovate",'0')
          status=false
        }
      }
    }

  }
}
</script>

<style >
#headDiv {
  width: 100%;
  background-color: white;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 5px 10px gray;
}
</style>